<?php

namespace app\common\tui;

class Push 
{
    private $url = "https://fc-mp-d3cd12a8-23d8-42e7-9efe-567980655450.next.bspapp.com/unipush";
    private $type = [
        'store' => '__UNI__08A4DA0',
        'rider' => '',
        'user' => '',
    ];
    /**
     * @param string $url 请求网址
     * @param bool $params 请求参数
     * @param bool $type 类型 store ，rider ，user
     * @param bool $post 请求方式，是否是post
     * @param bool $https 请求http协议，是否是https
     * @return bool|mixed
     */
    public function push( $params = false, $type , $url="", $post = true, $https = true){
        $url = empty($url) ? $this->url : $url;
        $params = [
            'appId' => $this->type[$type],
            'push_clientid' => $params['cid'],
            'title' => $params['title'],
            'content' => $params['content'],
            'payload' => [
                'order_status' => $params['state'],
                'mp3' => $params['mp3']
            ]
        ];
        $params = json_encode($params);
        $httpInfo = array();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            if ($post === true) {
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                curl_setopt($ch, CURLOPT_URL, $url);
            } else {
                if ($params === false) {
                    curl_setopt($ch, CURLOPT_URL, $url);
                } else {
                    if (is_array($params)) {
                        $params = http_build_query($params);
                    }
                    curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
                }
            }

            if ($https === true) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
            }
            $response = curl_exec($ch);
            if ($response === false) {
                // Illuminate\Support\Facades\Log::error();
                $data = sprintf('curl 错误。 url:%s, error:%s', $url, curl_error($ch));
                var_dump($data);exit;
                return false;
            }
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
            curl_close($ch);
            return $response;
    }
}